import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Res,
  Req,
  Session,
  UseInterceptors,
  ClassSerializerInterceptor,
} from '@nestjs/common';
import { UserService } from './user.service';
import {
  CreateUserDto,
  GetUserDto,
  LoginUserDto,
  UpdateMyPasswordDto,
  UpdatePasswordDto,
  UpdateUserDto,
} from './dto/user.dto';
import { PasswordPipe } from './pipe/password.pipe';
import { Request, Response } from 'express';
import { User } from 'src/database/user.entity';
import { UserEntity } from './entities/user.entity';
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  create(@Body(new PasswordPipe()) createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  @Post('/getAll')
  findAll(@Body() body: GetUserDto) {
    return this.userService.findAll(body);
  }

  // 更新密码
  @Post('/updatePassword')
  updatePassword(@Body() body: UpdatePasswordDto) {
    return this.userService.updatePassword(body);
  }

  // 更新自己的密码
  @Post('/updateMyPassword')
  updateMyPassword(@Body() body: UpdateMyPasswordDto, @Req() req: Request) {
    const token = req.headers.authorization;
    return this.userService.updateMyPassword(body, token);
  }

  // 获取自己的信息
  @Get('/my')
  findMy(@Req() req: Request) {
    const token = req.headers.authorization;
    return this.userService.findMy(token);
  }
  @Get(':id')
  async findOne(@Param('id') id: string): Promise<UserEntity> {
    const res: User = await this.userService.findOne(+id);
    return new UserEntity(res);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(+id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id);
  }

  // 获取验证码
  @Get('/captcha/getCode')
  getCaptcha(
    @Req() req: Request,
    @Res({ passthrough: true }) response: Response,
    @Session() session: Record<string, any>,
  ) {
    const captcha = this.userService.getCaptcha();
    session.captcha = captcha.text;
    session.cookie.maxAge = 20 * 1000;
    return captcha.data;
  }

  // 登录
  @Post('/login')
  login(
    @Body() body: LoginUserDto,
    @Session() session: Record<string, any>,
    @Req() req: Request,
  ) {
    return this.userService.login(body, session, req);
  }

  // 分配角色
  @Post('/assignRole')
  assignRole(@Body() body: { userId: number; roleIds: number[] }) {
    return this.userService.assignRole(body);
  }

  // 获取用户的角色
  @Get('/getRoles/:id')
  getRoles(@Param('id') id: string) {
    return this.userService.getUserRoles(+id);
  }
}
